import subprocess

from InquirerPy import inquirer
from prompt_toolkit.document import Document
from prompt_toolkit.validation import Validator, ValidationError


def find_nginx_expose_port():
    # 定义文件路径
    file_path = "/root/dify/docker/.env"

    # 初始化变量用于存储找到的值
    nginx_port = None

    try:
        # 打开文件并逐行读取
        with open(file_path, 'r') as file:
            for line in file:
                # 去除行首行尾的空白字符
                line = line.strip()
                # 检查是否包含关键字
                if line.startswith("EXPOSE_NGINX_PORT="):
                    # 使用 '=' 切分字符串，并取第二个值
                    parts = line.split('=')
                    if len(parts) > 1:
                        nginx_port = parts[1]
                        break  # 找到后退出循环

        # 输出结果
        return nginx_port

    except FileNotFoundError:
        print(f"文件未找到: {file_path}")
    except Exception as e:
        print(f"发生错误: {e}")


def main():
    nginx_expose_port = find_nginx_expose_port()

    class PortValidator(Validator):

        def validate(self, document: Document) -> None:
            if not document or not document.text:
                raise ValidationError(message='非法输入')
            port = int(document.text)
            if port < 0 or port > 65535:
                raise ValidationError(message='请输入合法的端口号')
            netstat_cmd = f"netstat -tuln | awk '{{print $4}}' | grep -v {nginx_expose_port} | grep {document.text}"
            running_port = subprocess.Popen(netstat_cmd, shell=True, stdout=subprocess.DEVNULL,
                                            stderr=subprocess.DEVNULL)
            running_port.wait()
            if running_port.returncode == 0:
                invalid_message = f"输入端口{port}被占用，请更换"
                raise ValidationError(message=invalid_message)

    change_port = inquirer.confirm(f'dify将以{nginx_expose_port}端口启动， 是否变更？', default=False).execute()
    if change_port:
        nginx_expose_port = inquirer.text(
            message="【注意】80 443 8080 8443这几个端口访问需要备案才能使用外网访问\n 请输入新的端口号:",
            default='8888', validate=PortValidator()
        ).execute()
        subprocess.Popen(
            f"sed -i 's#EXPOSE_NGINX_PORT=.*#EXPOSE_NGINX_PORT={nginx_expose_port}#g' /root/dify/docker/.env",
            shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).wait()

    subprocess.Popen("docker compose --file /root/dify/docker/docker-compose.yaml up -d", shell=True).wait()


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
